package com.icarbonx.dap.notification.util

import java.io.{BufferedReader, InputStream, InputStreamReader}
import java.net.{HttpURLConnection, URL, URLConnection}

import com.google.gson.JsonParser

/**
 * Created by Lenovo on 2018/8/19.
 */
object HttpGetRequest {
  def doGet(apiUrl: String, pid: String): Boolean = {
    var result = false
    var inputStream: InputStream = null
    var inputStreamReader: InputStreamReader = null
    var reader: BufferedReader = null
    val resultBuffer: StringBuffer = new StringBuffer
    try {
      val url = "https://mainapi.icarbonx.com/jarvis/medication/queryTemplate/" + pid
      val localURL: URL = new URL(apiUrl + pid)
      val connection: URLConnection = localURL.openConnection
      val httpURLConnection: HttpURLConnection = connection.asInstanceOf[HttpURLConnection]
      httpURLConnection.setRequestProperty("Accept-Charset", "utf-8")
      httpURLConnection.setRequestProperty("Content-Type", "application/json")
      var tempLine: String = null
      if (httpURLConnection.getResponseCode >= 300) {
        throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode)
      }
      inputStream = httpURLConnection.getInputStream
      inputStreamReader = new InputStreamReader(inputStream)
      reader = new BufferedReader(inputStreamReader)
      while ( {
        tempLine = reader.readLine;
        tempLine
      } != null) {
        resultBuffer.append(tempLine)
      }

      if (null != resultBuffer && resultBuffer.toString.length > 0 &&
        new JsonParser().parse(resultBuffer.toString).getAsJsonObject.get("data") != null
      ) {
        result = true
        println(s"_____ pid  $pid \t drugList  ${resultBuffer.toString}")
      } else {
        println(s"_____ pid  $pid \t no drugList  ")
      }

    } catch {
      case e: Exception =>
        println(s"_____ pid  $pid \t ${e.getMessage}  ")
    } finally {
      if (reader != null) {
        reader.close()
      }
      if (inputStreamReader != null) {
        inputStreamReader.close()
      }
      if (inputStream != null) {
        inputStream.close()
      }
    }

    result
  }
}
